<template>
	<div>

		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>权限管理</el-breadcrumb-item>
			<el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>

		<el-card class="box-card">

			<el-row :gutter="18">
				<el-col :span="2">
					<el-button type="info" icon="el-icon-refresh">刷新</el-button>
				</el-col>
				<el-col :span="7">
					<el-button type="primary" icon="el-icon-plus" @click="addVisible=!addVisible">添加</el-button>
				</el-col>
			</el-row>

			<el-table :data="tableData" style="width: 100%">				
				<el-table-column prop="name" label="角色" width="180">
				</el-table-column>
				<el-table-column prop="status" label="状态">
					<template slot-scope="scope">
						<el-switch 
							@change="changeStatus(scope.row.id,$event)" v-model="scope.row.status"
							:active-value="1" 
							:inactive-value="0" 
							:disabled="scope.row.id==1?true:false"
							active-color="#13ce66" 
							inactive-color="#ff4949">
						</el-switch>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="操作">
					<template slot-scope="scope" v-if="scope.row.id !=1">
						<el-tooltip class="item" effect="dark" content="编辑" placement="top">
							<el-button type="success" icon="el-icon-edit" size="mini" @click="editDialog(scope.row)">
							</el-button>
						</el-tooltip>
						<el-tooltip class="item" effect="dark" content="删除" placement="top">
							<el-button type="danger" icon="el-icon-delete" size="mini" @click="del(scope.row)">
							</el-button>
						</el-tooltip>
						<el-tooltip class="item" effect="dark" content="权限分配" placement="top">
							<el-button type="primary" icon="el-icon-setting" size="mini" @click="authDialog(scope.row)">
							</el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>

		</el-card>
		
		<!-- 添加角色 -->
		<el-dialog
		  title="添加角色"
		  :visible.sync="addVisible"
		  align="left"
		  @close="closeAddDialog"
		  width="50%">
		  
		  <el-form :model="addForm" :rules="addFormRul" ref="addFormRef" label-width="100px">
			  
		      <el-form-item label="角色名称" prop="name" >
		        <el-input v-model="addForm.name" autocomplete="off"></el-input>
		      </el-form-item>
			  
			  <el-form-item label="状态" prop="status">
			      <el-switch 
				  :active-value="1"
				  :inactive-value="0"
				  active-color="#13ce66"
				  inactive-color="#ff4949"
				  v-model="addForm.status"></el-switch>
			  </el-form-item>			  
			  
		    </el-form>		  
		  
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="addVisible = false">取 消</el-button>
		    <el-button type="primary" @click="add" >确 定</el-button>
		  </span>
		</el-dialog>
		
		<!-- 编辑角色 -->
		<el-dialog
		  title="编辑角色"
		  :visible.sync="editVisible"
		  align="left"		  
		  width="50%">
		  
		  <el-form :model="editForm" :rules="editFormRul" ref="editFormRef" label-width="100px">
			  
		      <el-form-item label="角色名称" prop="name" >
		        <el-input v-model="editForm.name" autocomplete="off"></el-input>
		      </el-form-item>
			  
			  <el-form-item label="状态" prop="status">
			      <el-switch 
				  :active-value="1"
				  :inactive-value="0"
				  active-color="#13ce66"
				  inactive-color="#ff4949"
				  v-model="editForm.status"></el-switch>
			  </el-form-item>			  
			  
		    </el-form>		  
		  
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="editVisible = false">取 消</el-button>
		    <el-button type="primary" @click="edit" >确 定</el-button>
		  </span>
		</el-dialog>
		
		<el-dialog
		  :title="auth_title"
		  :visible.sync="authVisible"
		  @close="closeAuthDialog"
		  align="left"		  
		  width="50%">
				<div style="margin-bottom: 8px;">
					<el-checkbox v-model="checkedAllNode" size="small" @change="setCheckedAllNode" label="全部选中" border></el-checkbox>
					<el-checkbox v-model="checkedOpenNode" size="mini" @change="setCheckedOpenNode" label="全部展开" border></el-checkbox>
				</div>
			   
		  	  <el-tree 
				  :data="authData" 
				  :props="defaultProps" 
				  ref="treeRef"
				  show-checkbox
				  node-key="id"
				  @node-expand="handleNodeExpand"
				  :render-content="renderContent"
				  :default-checked-keys="defaultSelectNode">
			  </el-tree>
		  
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="authVisible = false">取 消</el-button>
		    <el-button type="primary" @click="subimtAuth" >确 定</el-button>
		  </span>
		</el-dialog>

	</div>
</template>

<script>
	export default {
		data() {
			return {
				tableData: [],
				authData:[],
				defaultProps: {
				  children: 'children',
				  label: 'name'
				},
				defaultSelectNode:[],
				auth_role_id:'',
				addVisible: false,
				auth_title:'分配权限',
				authVisible:false,
				checkedAllNode:false,
				checkedOpenNode:false,				
				addForm:{
					name:'',
					status:''
				},
				addFormRul:{
					name:[
						{ required: true, message: '请输入角色名称！', trigger: 'blur'},
						{ min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur'}
					]
				},
				editVisible:false,
				editForm:{
					id:'',
					name:'',
					status:''
				},
				editFormRul:{
					name:[
						{ required: true, message: '请输入角色名称！', trigger: 'blur'},
						{ min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur'}
					]
				}
			}
		},
		methods: {
			//获取列表数据
			getTableData() {
				this.$http.get('role').then(res => {
					if (res.data.code !== 200) return this.$message.error(res.data.msg);
					this.tableData = res.data.data;
				});
			},
			//修改状态
			changeStatus(id,status){
				this.$http.put(`role/${id}/state/${status}`).then(res =>{
					if(res.data.code !==200){
						this.getTableData();
						return this.$message.error(res.data.msg);
					}else{					
						return this.$message.success(res.data.msg);
					}
				});
			},
			//添加
			closeAddDialog(){
				this.$refs.addFormRef.resetFields();
			},
			//发起添加请求
			add(){
				this.$refs.addFormRef.validate(valid => {
					if(!valid) return this.$message.error("请输入正确的信息！");
					this.$http.post('role',this.addForm).then(res =>{
						if(res.data.code === 200){
							this.$message.success(res.data.msg);
							this.addVisible = false;
							this.getTableData();
						}else{
							this.$message.error(res.data.msg);
						}					
					});
					
				});
			},
			
			editDialog(row) {
				this.editForm.name = row.name;
				this.editForm.status = row.status;
				this.editForm.id = row.id;
				this.editVisible = true;
			},
			edit(){
				this.$refs.editFormRef.validate(valid => {
					if(!valid) return this.$message.error("请输入正确的信息！");
					this.$http.put(`role/${this.editForm.id}`,this.editForm).then(res =>{
						if(res.data.code === 200){
							this.$message.success(res.data.msg);
							this.editVisible = false;
							this.getTableData();
						}else{
							this.$message.error(res.data.msg);
						}					
					});
					
				});
			},
			del(row) {
				this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(() => {
					this.$http.delete(`role/${row.id}`).then(res=>{
						if(res.data.code === 200){
							this.$message.success(res.data.msg);
							this.getTableData();
						}else{
							this.$message.error(res.data.msg);
						}
					});			  
				}).catch(() => {
				  this.$message({
					type: 'info',
					message: '已取消删除'
				  });          
				});
			},
			authDialog(row){
				this.auth_title = "分配权限 - "+row.name;
				this.auth_role_id = row.id;				
				this.getAuthData();
				this.getDefaultSelect(row.id);
				this.authVisible = true;
								
			},
			closeAuthDialog(){
				this.authVisible = false;
				this.auth_role_id = '';
				this.defaultSelectNode = [];
				this.checkedAllNode = false;
				this.checkedOpenNode = false;
			},
			getAuthData(){
				this.$http.get('menu').then(res => {
					if(res.data.code !== 200) return this.$message.error(res.data.msg);	
					this.authData = res.data.data;					
					//console.log(res);
				});
			},
			getDefaultSelect(role_id){
				this.$http.get(`role/${role_id}`).then(res=>{
					if(res.data.code !== 200) return this.$message.error(res.data.msg);
					var smid = res.data.data.smid;
					this.defaultSelectNode = smid ? res.data.data.smid.split(',') : [];
				});
			},
			//全部选中
			setCheckedAllNode(){
				if(this.checkedAllNode){
					this.$refs.treeRef.setCheckedNodes(this.authData);
				}else{
					this.$refs.treeRef.setCheckedKeys([]);
				}
			},
			//全部展开
			setCheckedOpenNode(){				
				if(this.checkedOpenNode){
					for(var i in this.$refs.treeRef.store.nodesMap){
						this.$refs.treeRef.store.nodesMap[i].expanded = true;
					}					
					
				}else{
					for(var j in this.$refs.treeRef.store.nodesMap){
						this.$refs.treeRef.store.nodesMap[j].expanded = false;
					}					
				}
				this.changeCss();
			},
			renderContent(h, { node }) {
			    let classname = '';
				if (node.childNodes.length === 0) {
					classname = 'floatRight';
				} else if (node.childNodes.length > 0) {
					classname = 'clearFloat';
				}
			    return <span class={classname}>{node.label}</span>;
			},
			handleNodeExpand(){
				this.changeCss();
			},
			changeCss() {
			    this.$nextTick(() => {
			        var levelName = document.getElementsByClassName('floatRight');
			        for (var i = 0; i < levelName.length; i++) {
			            let parentNode = levelName[i].parentNode;
			            parentNode.style.cssFloat = 'left';
			            parentNode.style.styleFloat = 'left';
			        }
			        var clearFloat = document.getElementsByClassName('clearFloat');
			        for (var j = 0; j < clearFloat.length; j++) {
			            let parentNode = clearFloat[j].parentNode;
			            parentNode.style.clear = 'both';
			            parentNode.style.clear = 'both';
			        }
			    });
			},
			subimtAuth(){
				var selectNode = this.$refs.treeRef.getCheckedKeys(true).toString();
				this.$http.put(`role/auth/${this.auth_role_id}`,{'smid':selectNode}).then(res=>{
					if(res.data.code === 200){
						this.$message.success(res.data.msg);
						this.authVisible = false;
					}else{
						this.$message.error(res.data.msg);
					}
				});
				
			}
		},
		created() {
			this.getTableData();
	
	}
}
</script>

<style>
</style>
